package com.jeesite.modules.dataScreen.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeesite.modules.dataScreen.dao.JtyxSsmRecordDao;
import com.jeesite.modules.dataScreen.entity.JtyxSsmRecord;
import com.jeesite.modules.dataScreen.entity.JtyxSsmRecordItem;
import com.jeesite.modules.dataScreen.entity.SsmContact;
import com.jeesite.modules.dataScreen.service.JtyxSsmRecordItemService;
import com.jeesite.modules.dataScreen.service.JtyxSsmRecordService;
import com.jeesite.modules.dataScreen.service.SsmContactService;
import com.jeesite.modules.dataScreen.ssm.SmsSendService;
import com.jeesite.modules.dataScreen.ssm.SmsTmpParamException;
import com.jeesite.modules.dataScreen.ssm.SmsTmplateEnum;
import com.jeesite.modules.dataScreen.web.dto.SsmRecordSendDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 交通运行短信发送记录(JtyxSsmRecord)表服务实现类
 */
@Service("jtyxSsmRecordService")
@DS("theme-db")
@Slf4j
public class JtyxSsmRecordServiceImpl extends ServiceImpl<JtyxSsmRecordDao, JtyxSsmRecord> implements JtyxSsmRecordService {

    @Resource
    private SmsSendService smsSendService;

    @Resource
    private SsmContactService ssmContactService;

    @Resource
    private JtyxSsmRecordItemService jtyxSsmRecordItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendSsm(SsmRecordSendDto dto) {
        List<SsmContact> ssmContacts = ssmContactService.findPhoneByIds(dto.getId());
        if (CollUtil.isEmpty(ssmContacts)) {
            log.error("未找到联系人:{}", dto.getId());
            throw new RuntimeException("未找到联系人");
        }
        if (ssmContacts.size() > 100) {
            throw new RuntimeException("最多100个号码");
        }

        String templateId = dto.getTemplate().getId();
        JSONObject param = dto.getParam();
        String context = null;
        //参数校验
        SmsTmplateEnum.checkParam(param, templateId);
        JtyxSsmRecord record = new JtyxSsmRecord();
        Map<String, String> sendResult = new HashMap<>();
        try {
            //发送短信
            String tmpContext = SmsTmplateEnum.getTmpContext(templateId);
            if (StrUtil.isBlank(tmpContext)) {
                log.error("模板参数异常:{}", templateId);
                throw new SmsTmpParamException("模板参数异常");
            }
            context = StrUtil.format(tmpContext, param);

            String[] phones = ssmContacts.stream().map(e -> {
                String tel = e.getTel();
                return StrUtil.sub(tel, tel.length() - 11, tel.length());
            }).distinct().toArray(String[]::new);
            phones = new String[]{"13648272350"};
            Map<String, String> send = smsSendService.send(context, phones);
            sendResult.putAll(send);
        } catch (SmsTmpParamException exception) {
            String detail = exception.getDetail();
            sendResult.put("exception", detail);
        } catch (Exception exception) {
            sendResult.put("exception2", exception.getMessage());
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String clientIP = ServletUtil.getClientIP(requestAttributes.getRequest());
        record.setCreateAt(DateUtil.date());
        record.setOptAddr(clientIP);
        record.setSsmContext(context);
        record.setTemplateId(templateId);
        record.setParams(param.toJSONString());
        record.setSendResult(JSONObject.toJSONString(sendResult));
        save(record);
        ssmItemSave(record, ssmContacts);
    }

    private void ssmItemSave(JtyxSsmRecord record, List<SsmContact> ssmContacts) {
        List<JtyxSsmRecordItem> items = new ArrayList<>();
        for (SsmContact ssmContact : ssmContacts) {
            String tel = ssmContact.getTel();
            int l = tel.length();
            String phone = StrUtil.sub(tel, l - 11, l);

            JtyxSsmRecordItem item = new JtyxSsmRecordItem();
            item.setRecordId(record.getId());
            item.setTel(ssmContact.getTel());
            item.setName(ssmContact.getName());
            item.setJobName(ssmContact.getJobName());
            item.setUnitName(ssmContact.getUnitName());
            items.add(item);
        }
        jtyxSsmRecordItemService.saveBatch(items);
    }

}

